/*
 * Copyright 2011-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package xyz.ewangshi.jdbc;

import java.text.MessageFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.management.RuntimeErrorException;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

/**
 * @author ewangshi
 * 2016-07-06
 */
public class SQLSupport implements SqlOperations {
	private static final Map<String, SQLBean> SQLMAP = new LinkedHashMap<String, SQLBean>();

	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	@Override
	public SQLBean getSQLBeanById(String id) {
		SQLBean bean = null;

		if (null == id || id.isEmpty()) {
			throw new RuntimeException("sqlId can not be empty");
		} else {
			bean = SQLMAP.get(id);
		}

		return bean;
	}

	@Override
	public <T> List<T> query(String id, Map<String, ?> map, RowMapper<T> rowMapper) {
		SQLBean sqlBean = getSQLBeanById(id);
		String sql = bindSql(sqlBean, map);
		return namedParameterJdbcTemplate.query(sql, map, rowMapper);
	}
	
	@Override
	public int insert(String id, Map<String, ?> paramMap) {
		SQLBean sqlBean = getSQLBeanById(id);
		String sql = bindSql(sqlBean, paramMap);
		return namedParameterJdbcTemplate.update(sql, paramMap);
	}

	@Override
	public int update(String id, Map<String, ?> paramMap) {
		SQLBean sqlBean = getSQLBeanById(id);
		String sql = bindSql(sqlBean, paramMap);
		return namedParameterJdbcTemplate.update(sql, paramMap);
	}

	@Override
	public int delete(String id, Map<String, ?> paramMap) {
		SQLBean sqlBean = getSQLBeanById(id);
		String sql = bindSql(sqlBean, paramMap);
		return namedParameterJdbcTemplate.update(sql, paramMap);
	}

	@Override
	public int[] batchUpdate(String id, Map<String, ?>[] batchValues) {
		SQLBean sqlBean = getSQLBeanById(id);
		String sql = bindSql(sqlBean, batchValues[0]);
		return namedParameterJdbcTemplate.batchUpdate(sql, batchValues);
	}

	public static void putSQLMAP(String key, SQLBean bean) {
		if (SQLMAP.containsKey(key)) {
			throw new RuntimeErrorException(new Error("Duplicate sqlId, sqlId: " + key));
		} else {
			SQLMAP.put(key, bean);
		}
	}

	private String bindSql(SQLBean sqlBean, Map<String, ?> map) {
		List<SqlParam> params = sqlBean.getParams();
		String[] arr = new String[params.size()];
		
		for (int i = 0; i < params.size(); i++) {
			SqlParam sqlParam = params.get(i);
			if (map.containsKey(sqlParam.getKey()) && null != map.get(sqlParam.getKey())) {
				if(sqlParam.isStr()){
					arr[i] = map.get(sqlParam.getKey()).toString() ;
				}else{
					arr[i] = sqlParam.getSqlStr();
				}
			} else {
				arr[i] = "";
			}
		}
		MessageFormat mf = new MessageFormat(sqlBean.getSqlPart());
		return mf.format(arr);
	}

	public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
		return namedParameterJdbcTemplate;
	}

	public void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
		this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
	}
}
